package com.jzo2o.orders.manager.hander;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.jzo2o.common.constants.UserType;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.orders.base.model.domain.Orders;
import com.jzo2o.orders.base.model.domain.OrdersRefund;
import com.jzo2o.orders.manager.model.dto.OrderCancelDTO;
import com.jzo2o.orders.manager.service.IOrdersManagerService;
import com.jzo2o.orders.manager.service.IOrdersRefundService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Component
public class OrdersHandler {
    @Resource
    private IOrdersManagerService ordersManagerService;

    @Resource
    private IOrdersRefundService ordersRefundService;

    /**
     * 支付超时取消订单
     * 每分钟执行一次
     */
    @XxlJob(value = "cancelOverTimePayOrder")
    public void cancelOverTimePayOrder() {
        //查询支付超时状态订单
        List<Orders> ordersList = ordersManagerService.queryOverTimePayOrdersListByCount(100);
        if (CollUtil.isEmpty(ordersList)) {
            XxlJobHelper.log("查询超时订单列表为空！");
            return;
        }

        for (Orders orders : ordersList) {
            //取消订单
            OrderCancelDTO orderCancelDTO = BeanUtil.toBean(orders, OrderCancelDTO.class);
            orderCancelDTO.setCurrentUserType(UserType.SYSTEM);
            orderCancelDTO.setCancelReason("订单超时支付，自动取消");
            ordersManagerService.cancelNoPayOrder(orderCancelDTO);
        }
    }

    /**
     * 退款定时任务
     */
    @XxlJob("handleRefundOrders")
    public void handleRefundOrders(){
        //查询退款记录表
        List<OrdersRefund> ordersRefunds = ordersRefundService.queryRefundOrderListByCount(100);
        if(CollUtils.isEmpty(ordersRefunds)){
            log.info("退款定时任务，未查询到订单的退款记录");
            return ;
        }
        //遍历退款记录，请求支付服务进行退款
        for (OrdersRefund ordersRefund : ordersRefunds) {
            //请求支付服务进行退款，并且 将退款结果更新到订单表中
            ordersManagerService.requestRefundOrder(ordersRefund);
        }
    }
}